package springboot.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import springboot.tool.ConvertByteToBit;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SimpleServerHandler extends ChannelInboundHandlerAdapter {

    public static List<Channel> channels = new ArrayList<>();
    public static boolean PLC_IS_ONLINE=false;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel inChannel=ctx.channel();
        if(channels.size()==0){//如果没有连接就进行连接就对了
            channels.add(inChannel);
            System.out.println("=== " + ctx.channel().remoteAddress() + " is active ===");

        }
    }

    public static byte[] DATA=new byte[24];
    public static byte[] STACK=null;
    public static byte[] PALLET=null;
    public static byte LOAD_YES=0;
    public static byte UNLOAD_YES=0;
    public static byte AGV_FORBID=0;
    public static byte PEOPLE_ENTRY_A=0;
    ConvertByteToBit convertByteToBit=new ConvertByteToBit();
    byte[] bytes=null;
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws InterruptedException, IOException {
        ByteBuf buf = (ByteBuf) msg;
        bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        if (bytes[0]==2&&bytes[1]==7&&bytes[2]==86&&bytes[11]==3){
            //业务用到的数据
            LOAD_YES=bytes[4];
            UNLOAD_YES=bytes[5];
            AGV_FORBID=bytes[6];
            STACK=convertByteToBit.byteToBit(bytes[7]);
            PALLET=convertByteToBit.byteToBit(bytes[8]);
            PEOPLE_ENTRY_A=bytes[9];
            PLC_IS_ONLINE=true;//刷新过数据之后才能给调度使用
        }

        //Manual recycling to prevent memory leakage;
        ReferenceCountUtil.release(buf);
        /**
         * 报文发送数据
         */
        DATA[0] = 2;//报文头
        DATA[1] = 20;//有效的数据长度
        DATA[2] = 86;//标志位
        DATA[3]= (byte) (DATA[3]+1);//DATA[3]作为心跳存在
        DATA[22] = 0;//和校验
        DATA[23] = 3;//报文尾

        ByteBuf json = Unpooled.wrappedBuffer(DATA);
        ctx.writeAndFlush(json);
    }
}
